import { defineStore } from 'pinia';
import { PERMISSIONS_STORE } from '../constant';
import { computed, ref } from 'vue';
import { getRouters } from '@/api/menus';
import { generateDynamicRoutes } from '@/router/helper/routerHelper';
import type { RouteRecordRaw } from 'vue-router';
import router from '@/router';
import { useUserStore } from './user';
import { useRoute } from 'vue-router';

export const usePermissionsStore = defineStore(PERMISSIONS_STORE, () => {
  const route = useRoute();

  const menus = ref<RouteRecordRaw[]>([]);
  const GenerateRoutes = async () => {
    const res = await getRouters();
    const userStore = useUserStore();
    menus.value = generateDynamicRoutes(res.data, userStore.isAdmin);
  };
  const setCurrentNav = (value: string[]) => {
    const menu = menus.value.find((menu) => menu.path === value[0]);
    if (menu) {
      router.push(menu!.path!);
    }
  };

  const subMenus = computed<RouteRecordRaw[]>(() => {
    const match = route.fullPath.match(/^\/[^/]+/);
    if (match) {
      const result = menus.value.find((menu) => menu.path === match[0]);
      return result?.children || [];
    } else {
      return [];
    }
  });

  const currentNav = computed(() => {
    const match = route.fullPath.match(/^\/[^/]+/);
    if (match) {
      return [match[0]];
    } else {
      return [];
    }
  });

  const cleanMenus = () => {
    menus.value = [];
  };

  return {
    menus,
    currentNav,
    subMenus,
    GenerateRoutes,
    setCurrentNav,
    cleanMenus,
  };
});
